class User < ActiveRecord::Base
  has_many                :entries
  has_many                :comments
  has_and_belongs_to_many :roles
  has_and_belongs_to_many :weblogs

  attr_accessor :cleartext_password, :terms

  validates_presence_of     :username,           :cleartext_password, :email, :logo
  validates_length_of       :username,           :in => 6..20, :if => Proc.new { |u| !u.username.blank? }
  validates_length_of       :cleartext_password, :in => 8..32, :if => Proc.new { |u| !u.cleartext_password.blank? }
  validates_confirmation_of :cleartext_password
  validates_format_of       :email,              :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :if => Proc.new { |u| !u.email.blank? }
  validates_acceptance_of   :terms
  validates_uniqueness_of   :username, :email,   :case_sensitive => false

  before_save :before_save

  def self.authenticate(username, cleartext_password)
    user = find_by_username username

    user && user.password == encrypt(user.salt, cleartext_password) ? user : nil
  end

  def self.encrypt(*objects)
    Digest::SHA1.hexdigest objects.inject('--') { |s, o| s += o.to_s + '--' }
  end

  def logo_file=(logo_field)
    self.logo = logo_field.read
  end

  def remember_me_valid?
    remember_me_expires && Time.now.utc < remember_me_expires
  end

  private
  def before_save
    return if cleartext_password.blank?

    self.salt     = self.class.encrypt Time.now, username if new_record?
    self.password = self.class.encrypt salt, cleartext_password
  end
end
